<?php
	class GP_template
	{
		static $_instance;
		public $fictpl;
		public $type;
		public $page;
		public $header;
		public $footer;
		public $delim_gauche = '{{';
		public $delim_droite = '}}';
		
		// singleton
		public function &getInstance($tpl, $type = 'html') 
		{
			if (!self::$_instance instanceof self)
				self::$_instance = new self($tpl, $type);
			return self::$_instance;
		}
		
		public function __construct($tpl, $type = 'html')
		{
			$this -> fictpl = $tpl;
			$this -> type = $type;
			self::charger_page();
		}
		
		public function charger_page() 
		{
			$tpl = DIR_HTML . $this -> fictpl . '.' . $this -> type;
			
			$id_tpl = md5($tpl . session_id() . APPLNG . REQUESTURI);
			
			// gestion du cache html
			if (TPL_CACHE == true && $this -> type == 'html')
			{
				if(is_file(DIR_CACHE . $id_tpl . '.cache') && (time() - filemtime(DIR_CACHE . $id_tpl . '.cache')) <= CACHE_DUREE)
					$this -> page = DIR_CACHE . $id_tpl . '.cache';
				else
				{
					if (!strlen($this -> fictpl) || !@file_exists($tpl)) 
						$tpl = ERROR_TPL;
					else
						$this -> page = GP_fonctions::html2($tpl);
					
					if ($this -> type == 'html')
					{
						self::transformer_html();
						self::fabriquer_html();
						$cachefic = DIR_CACHE . $id_tpl . '.cache'; 
						@unlink($cachefic);
						@touch($cachefic);
						$fp = fopen($cachefic, 'a');
						fwrite($fp, implode('', file($this -> page)));
						fclose($fp);
						@unlink($this -> page);
						$this -> page = $cachefic;
					}
				}
			}
			
			// fin gestion du cache html
			else
			{
				if (!strlen($this -> fictpl) || !@file_exists($tpl)) 
					$tpl = ERROR_TPL;
				else
					$this -> page = GP_fonctions::html2($tpl);
				
				if ($this -> type == 'html')
				{
					self::transformer_html();
					self::fabriquer_html();
				}
			}
		}
		
		public function transformer_html()
		{
			$var_str = $this -> delim_gauche . '=';
			$this -> page = str_replace($var_str, '<?php echo ', $this -> page);
			
			$var_str = $this -> delim_gauche;
			$this -> page = str_replace($var_str, '<?php ', $this -> page);
			
			$var_str = $this -> delim_droite;
			$this -> page = str_replace($var_str, ' ?>', $this -> page);
		}
		
		public function fabriquer_html()
		{
			$nom_fic = DIR_TMP . md5($this -> page) . '.html';
			@unlink($nom_fic);
			@touch($nom_fic);
			$fp = fopen($nom_fic, 'a');
			fwrite($fp, $this -> page);
			fclose($fp);
			
			$this -> page = $nom_fic;
		}
	}
?>